/* zengyongguang 2017-7-28 */
'use strict';
var md5 = require('../../utils/crypto').md5;
var db = require('../../utils/db');
var http = require('../../utils/http');
var http = require('../../utils/http');
var tools = require('../../utils/tools');
var config = require('../../configs_local').hall_server();
var key = "244ca72c106b8eef6c27f2e97bfd93ee";
var customerid = "155038";
var mark = "test";
var gemsConfig = {}
var finishList = {}

var log4js = require('log4js');
var log = log4js.getLogger("pay");
setTimeout(function () {
    if (!Object.keys(gemsConfig).length) {
        db.get_pay_config()
            .then(function (ret) {
                ret.forEach(function (conf) {
                    gemsConfig[conf.money] = conf.give + conf.gem;
                });
            }).catch(function (err) {
                log.warn(err)
            });
    }

}, 1000)



var httpSend = function (res, respcode, errcode, errmsg, data) {
    if (data == null) {
        data = {};
    }
    data.respCode = respcode;
    if (data.errorCode) {
        data.errorCode = errcode;
    }
    if (data.respMsg) {
        data.respMsg = errmsg;
    }
    var jsonstr = JSON.stringify(data);
    res.send(jsonstr);
};



/**
 * 创建支付订单
 * @param {Object} args 
 * @param {Ojbect} res 
 */
var createPayOrder = function (args, res) {

    /* check callpay args */
    if (!(args.userId && args.sdcustomno &&
        args.type && args.money && args.payment && args.state)) {

        return http.send(res, 1, "createPayOrder args is error");
    }

    if (gemsConfig[args.money]) {
        args.gems = gemsConfig[args.money];
        return db.create_order(args)
            .then(function (status) {
                log.debug("create order success ", status);
                var url = "http://" + config.HALL_IP + ":" + config.CLEINT_PORT + "/pay_callback";
                log.debug(url);
                return http.send(res, 0, { url: url });
            });
    } else {
        return http.send(res, -1, "createPayOrder args money error");
    }

};


/**
 * 支付回调
 * @param {Object} callbackArgs 
 * @param {Object} res 
 */
var payCallback = function (callbackArgs, res) {
    /* check callpay args */
    if (!(callbackArgs.customerid &&
        callbackArgs.sd51no && callbackArgs.sdcustomno &&
        callbackArgs.ordermoney && callbackArgs.cardno && callbackArgs.sign)) {
        return httpSend(res, '03', 1001, "ballback args is error");
    }
    /* sign validate */
    var sign = md5("customerid=" + callbackArgs.customerid + "&sd51no=" + callbackArgs.sd51no + "&sdcustomno=" +
        callbackArgs.sdcustomno + "&mark=" + callbackArgs.mark + "&key=" + key).toUpperCase();
    if (sign !== callbackArgs.sign) {
        return httpSend(res, '03', 1001, "sign error");
    }

    //  check is callback
    db.get_orderstatus_by_sdcustomno(callbackArgs.sdcustomno)
        .then(function (orderInfo) {
            if (orderInfo.state === 1) {
                return httpSend(res, '00');
            } else {
                if (finishList[callbackArgs.sdcustomno]) {
                    return httpSend(res, '00');
                }
                finishList[callbackArgs.sdcustomno] = true;
                var updateOrderAndGems = function (query) {
                    return db.update_order(callbackArgs.sdcustomno, callbackArgs.state, query)
                        .then(function (status) {
                            delete finishList[callbackArgs.sdcustomno]; // 清除状态
                            log.debug("update order status is ", status);
                            return db.get_order_userId_bySdcustomno(callbackArgs.sdcustomno, query);
                        }).then(function (userId) {
                            var gems = gemsConfig[parseFloat(callbackArgs.ordermoney)];
                            log.debug("get order userid ", userId, gems);
                            return db.update_user_gems(userId, gems, orderInfo.type, query);
                        }).then(function (status) {
                            log.debug("update user gem status is ", status);
                            return status;
                        });
                };

                //  事务处理更新
                db.beginTransaction(updateOrderAndGems)
                    .then(function (status) {
                        return httpSend(res, '00');
                    }).catch(function (err) {
                        return httpSend(res, '03', 1001, "update order erro");
                    });
            }
        });
};


/**
 * 检查用户支付状态并返回用户的房卡
 * @param {String} sdcustomno 
 * @param {Number} userId 
 * @param {Object} res 
 */
var checkAndSetUserPayStautsAndReturnGems = function (sdcustomno, userId, type, res) {
    db.get_orderstatus_by_sdcustomno(sdcustomno)
        .then(function (orderInfo) {
            if (orderInfo.state !== 1) {
                if (finishList[callbackArgs.sdcustomno]) {
                    /* search  usermoney*/
                    db.get_user_gems(userId, type)
                        .then(function (gems) {
                            http.send(res, 0, { gems: gems });
                        }).catch(function (err) {
                            http.send(res, -1, err);
                        });
                }
                finishList[callbackArgs.sdcustomno] = true;
                var sign = md5("customerid=" + customerid + "&sdcustomno=" +
                    sdcustomno + "&mark=" + mark + "&key=" + key).toUpperCase();
                var url = "http://www.zhifuka.net/gateway/zx_orderquery.asp";
                // console.log()
                http.getPay(url, { customerid: customerid, sdcustomno: sdcustomno, mark: mark, sign: sign })
                    .then(function (item) {
                        return tools.xmlToJson(item);
                    }).then(function (data) {
                        log.debug(data);
                        if (data.state === 1) {
                            /* update data */
                            var updateOrderAndGems = function (query) {
                                return db.update_order(sdcustomno, data.state, query)
                                    .then(function (status) {
                                        delete finishList[callbackArgs.sdcustomno]  // 清除状态
                                        log.debug("update order status is ", status);
                                        var gems = gemsConfig[parseFloat(data.ordermoney)];
                                        return db.update_user_gems(userId, gems, orderInfo.type, query);
                                    }).then(function (status) {
                                        log.debug("update user gem status is ", status);
                                        return status;
                                    });
                            };
                            //  事务处理更新
                            db.beginTransaction(updateOrderAndGems)
                                .then(function () {
                                    /* search  usermoney*/
                                    return db.get_user_gems(userId, orderInfo.type);
                                }).then(function (gems) {
                                    http.send(res, 0, { gems: gems });
                                })
                                .catch(function (err) {
                                    return http.send(res, 1, "update order error " + err);
                                });
                        } else {
                            /* search  usermoney*/
                            db.get_user_gems(userId, orderInfo.type)
                                .then(function (gems) {
                                    http.send(res, 0, { gems: gems });
                                }).catch(function (err) {
                                    http.send(res, -1, err);
                                });
                        }

                    });

            } else {
                /* search  usermoney*/
                db.get_user_gems(userId, orderInfo.type)
                    .then(function (gems) {
                        http.send(res, 0, { gems: gems });
                    }).catch(function (err) {
                        http.send(res, -1, err);
                    });
            }
        });


};

// setTimeout(function () {
//     checkAndSetUserPayStautsAndReturnGems('1501576703132', 119, {
//         send: function (status, data) {
//             console.log(status, data);
//         }
//     });
// }, 2000);

module.exports = {
    payCallback: payCallback,
    createPayOrder: createPayOrder,
    checkAndSetUserPayStautsAndReturnGems: checkAndSetUserPayStautsAndReturnGems
};